from rest_framework import serializers
from apps.headline.models import Channel, Article, Comment
from apps.person.models import User
from apps.person.serializers import ArticlePersonSerializer, PersonSerializer
from apps.qa.models import Label
from apps.spit.models import Spit


class LabelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Label
        fields = ['id','label_name']

class ChannelSerializer(serializers.ModelSerializer):
    channel_id = serializers.IntegerField(read_only=True)
    class Meta:
        model = Channel
        fields = '__all__'

class SpitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Spit
        fields = ['collected']

class ArticleSerializer(serializers.ModelSerializer):
    user = ArticlePersonSerializer(read_only=True)
    collected = serializers.BooleanField(default=False)

    class Meta:
        model = Article
        fields = ['id','title','content','createtime',
                  'user','collected_users','collected','image']

class SubSerializer(serializers.ModelSerializer):
    subs = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = Comment
        fields = ['id','user','subs','content','createtime',
                  'updatetime','parent','article']

class CommentsSerializer(serializers.ModelSerializer):
    user = ArticlePersonSerializer(read_only=True)
    subs = SubSerializer(read_only=True)
    class Meta:
        model = Comment
        fields = ['id','user','subs','content','createtime',
                  'updatetime','parent','article']

class ArticleDetailSerializer(serializers.ModelSerializer):
    user = ArticlePersonSerializer(read_only=True)
    collected_users = serializers.StringRelatedField(read_only=True)
    comments = CommentsSerializer(read_only=True)

    class Meta:
        model = Article
        fields = ['id','title','content','createtime','updatetime','visits','thumbup','comment_count',
                  'user','channel','labels','comments','collected_users','image']


class ArticleCreateSerializer(serializers.ModelSerializer):
    articleid = serializers.IntegerField(read_only=True)
    labels = LabelsSerializer(read_only=True)
    user_id = serializers.IntegerField(default='shier')
    class Meta:
        model = Article
        fields = ['user_id','articleid','content','labels','title','channel','image']

    def create(self, validated_data):

        # 调用父类方法--》保存新增的数据        
        article = super().create(validated_data)

        return article